<?php
	include("template.inc");
	require_once("scripts/global_2.php");
	require_once("scripts/constraint.php");
	require_once("scripts/EKUser.php");
	session_start();
	
	$template = new Template();
	$template->set_file("user","template/user.html");
	
	//set page title
	$template->set_var("pageTitle",SITENAME);
	
	$template->set_var("note", "");
	
	$template->set_var("containsView", "hidden");

    // method:
	// c: create new user (register)
	// e: edit user (modify user information)
	// v: view user (user view) 
	$type = $_GET["method"];
	$id = $_GET["userid"];
	
	if($type!="c" && $type!="e" )
	{
		$note = "<script language=javascript>\n".
				"alert(\"Missing parameters! Please visit this page from hyperlinks!\");\n".
				"history.go(-1);\n".
				"</script>";
		$template->set_var("note", $note);
	}
	 
	if($type=="c")
	{
		// this is the case of register
		try{
			EKUser::register($_POST["userid"],
			                 $_POST["password"],
			                 $_POST["username"],
			                 $_POST["email"],
			                 $_POST["selfIntro"]);
			                 
		    $note = "<script language=javascript>\n".
			"alert(\"Congratulations! ".$_POST["username"].", your account will checked by administrator later.'\");\n".
			"history.go(-2);\n".
			"</script>";
			$template->set_var("note", $note);
			$_SESSION = array();
	    	
		}catch(Exception $e)
		{
			$note = "<script language=\"javascript\">\n".
			        "alert(\"".$e->getMessage()."\");\n".
			        "history.go(-1);\n".
			        "</script>";
			$template->set_var("note", $note);
		}
	}
	
	if($type=="e")
	{
		// this is the case of modify
		try{
			EKUser::updateDB($_SESSION["userid"],"password",$_POST["password"]);
			EKUser::updateDB($_SESSION["userid"],"name",$_POST["username"]);
			EKUser::updateDB($_SESSION["userid"],"email",$_POST["email"]);
			EKUser::updateDB($_SESSION["userid"],"selfIntro",$_POST["selfIntro"]);
			$note = "<script language=javascript>\n".
			"alert(\"The personal information has been modified successfully!\");\n".
			"history.go(-2);\n".
			"</script>";
			$template->set_var("note", $note);
		}catch(Exception $e)
		{
			$note = "<script language=javascript>\n".
			        "alert(\"".$e->getMessage()."\");\n".
			        "history.go(-1);\n".
			        "</script>";
			$template->set_var("note", $note);
		}
	}
	
	//parse & generate the output
	$template->parse("output","user");
	$template->p("output");
?>